import 'dart:async';

import 'package:flutter/material.dart';

class CounterHome extends StatelessWidget {
  const CounterHome({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    CounterBloC _bloC = CounterProvider.of(context).bloC;
    return Center(
      child: StreamBuilder(
        initialData: 0,
        stream: _bloC.count,
        builder: (context, snapShot){
          return ActionChip(
            label: Text('${snapShot.data}'),
            onPressed: (){
              _bloC.counter.add(1);
            },
          );
        }
      )
    );
  }
}

class CounterAcitonButton extends StatelessWidget {
  const CounterAcitonButton({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    CounterBloC _bloC = CounterProvider.of(context).bloC;
    return FloatingActionButton(
      child: Icon(Icons.add), 
      onPressed: (){
        _bloC.counter.add(1);
      }
    );
  }
}

class CounterProvider extends InheritedWidget {
  CounterProvider({Key key, this.child,this.bloC}) : super(key: key, child: child);

  final Widget child;
  final CounterBloC bloC;

  static CounterProvider of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<CounterProvider>();
  }

  @override
  bool updateShouldNotify(CounterProvider oldWidget) {
    return true;
  }
}

class CounterBloC {
  int _count = 0;

  final _counterActionController = StreamController<int>();
  StreamSink<int> get counter => _counterActionController.sink;

  final _counterController = StreamController<int>();
  Stream<int> get count => _counterController.stream;

  CounterBloC(){
    _counterActionController.stream.listen(onData);
  }
  void onData(int data) {
    print('$data');
    _count = data + _count;
    _counterController.add(_count);
  }
  void dispose(){
    _counterActionController.close();
  }
  void log(){
    print('BLoC');
  }
}
